#include "AT.h"

#include <QDebug>
#include <utility>
#include "utils/StringUtils.h"

AT::AT(AT::SendDelegate delegate)
    : _sendDelegate(std::move(delegate)) {
}

std::string AT::cmd(const char* cmd, uint32_t waitMs) {
    _buf.clear();
    auto str = StringUtils::format("AT+%s\r", cmd);
    _sendDelegate(str.data(), str.length());
    delayMs(waitMs);
    return _buf;
}

std::string AT::raw(std::string cmd, uint32_t waitMs) {
    _buf.clear();
    _sendDelegate(cmd.data(), cmd.length());
    delayMs(waitMs);
    return _buf;
}

void AT::delayMs(uint32_t ms) {
    std::unique_lock<std::mutex> guard(_mutex);
    _cond.wait_for(guard, std::chrono::milliseconds(ms));
}

void AT::onData(std::string data) {
    qDebug()<< "*************onData: \n" << data.c_str();
    _buf += data;
    qDebug()<< "*************end";
}
